<template>
  <view class="device-detail-page">
    <scroll-view scroll-y class="page-content">
      <!-- 设备图片轮播 -->
      <view class="image-section">
        <swiper 
          class="device-swiper" 
          :autoplay="false" 
          :indicator-dots="true"
          indicator-color="rgba(255,255,255,0.5)"
          indicator-active-color="#fff"
          @change="onSwiperChange"
        >
          <swiper-item v-for="(image, index) in deviceInfo.images" :key="index">
            <image 
              :src="image || '/static/placeholder-device.png'"
              class="device-image"
              mode="aspectFill"
              @click="previewImage(index)"
            />
          </swiper-item>
        </swiper>
        
        <!-- 图片指示器 -->
        <view class="image-indicator">
          {{ currentImageIndex + 1 }} / {{ deviceInfo.images?.length || 0 }}
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-buttons">
          <view class="action-btn" @click="toggleFavorite">
            <u-icon 
              :name="deviceInfo.isFavorite ? 'heart-fill' : 'heart'"
              :color="deviceInfo.isFavorite ? '#ff6b6b' : '#fff'"
              size="20"
            />
          </view>
          <view class="action-btn" @click="shareDevice">
            <u-icon name="share" color="#fff" size="20" />
          </view>
        </view>
      </view>

      <!-- 设备基本信息 -->
      <view class="info-card">
        <view class="device-header">
          <view class="title-section">
            <text class="device-title">{{ deviceInfo.title }}</text>
            <text class="device-subtitle">{{ deviceInfo.brand }} {{ deviceInfo.model }}</text>
          </view>
          <view class="status-badge" :class="getStatusClass(deviceInfo.status)">
            {{ getStatusText(deviceInfo.status) }}
          </view>
        </view>
        
        <view class="price-section">
          <view class="price-main">
            <text class="price-symbol">￥</text>
            <text class="price-amount">{{ deviceInfo.dailyRent || 0 }}</text>
            <text class="price-unit">/天</text>
          </view>
          <view class="price-secondary">
            <text class="deposit-text">押金: ￥{{ deviceInfo.deposit || 0 }}</text>
            <text class="rent-period">最少租期: {{ deviceInfo.minRentDays || 1 }}天</text>
          </view>
        </view>
        
        <!-- 快速操作 -->
        <view class="quick-actions">
          <view class="quick-btn" @click="checkAvailability">
            <u-icon name="calendar" size="18" color="#4A90E2" />
            <text class="btn-text">查看可租时间</text>
          </view>
          <view class="quick-btn" @click="calculateCost">
            <u-icon name="rmb" size="18" color="#4A90E2" />
            <text class="btn-text">费用计算</text>
          </view>
        </view>
      </view>

      <!-- 设备规格参数 -->
      <view class="specs-card">
        <view class="card-header">
          <text class="card-title">设备参数</text>
          <text class="expand-btn" @click="specsExpanded = !specsExpanded">
            {{ specsExpanded ? '收起' : '展开' }}
            <u-icon :name="specsExpanded ? 'arrow-up' : 'arrow-down'" size="12" />
          </text>
        </view>
        
        <view class="specs-content" :class="{ expanded: specsExpanded }">
          <view class="specs-grid">
            <view 
              v-for="(value, key) in deviceInfo.specifications" 
              :key="key"
              class="spec-item"
            >
              <text class="spec-label">{{ key }}</text>
              <text class="spec-value">{{ value }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 设备描述 -->
      <view class="description-card">
        <text class="card-title">设备详情</text>
        <text class="description-text">{{ deviceInfo.description || '暂无详细描述' }}</text>
        
        <!-- 设备特点标签 -->
        <view v-if="deviceFeatures.length > 0" class="features-tags">
          <view v-for="feature in deviceFeatures" :key="feature" class="feature-tag">
            {{ feature }}
          </view>
        </view>
      </view>

      <!-- 位置信息 -->
      <view class="location-card">
        <view class="card-header">
          <text class="card-title">设备位置</text>
          <view class="location-actions">
            <text class="distance-text" v-if="deviceInfo.distance">距离 {{ deviceInfo.distance }}km</text>
            <u-button 
              type="primary" 
              size="mini"
              @click="navigateToDevice"
            >
              导航
            </u-button>
          </view>
        </view>
        
        <text class="location-address">{{ getFullAddress() }}</text>
        
        <map 
          :longitude="mapCenter.longitude"
          :latitude="mapCenter.latitude"
          :markers="mapMarkers"
          :scale="mapScale"
          class="location-map"
          show-location
          @tap="openLocationDetail"
        />
      </view>

      <!-- 联系信息 -->
      <view class="contact-card">
        <view class="card-header">
          <text class="card-title">联系方式</text>
        </view>
        <view class="contact-content">
          <view class="contact-item" @click="callContact">
            <u-icon name="phone" size="20" color="#4A90E2" />
            <text class="contact-text">{{ deviceInfo.contactPhone || '400-0000-000' }}</text>
            <text class="contact-label">点击拨打</text>
          </view>
          <view class="working-hours">
            <u-icon name="clock" size="16" color="#999" />
            <text class="hours-text">工作时间：9:00-18:00</text>
          </view>
        </view>
      </view>

      <!-- 出租方信息 -->
      <view class="owner-card">
        <text class="card-title">出租方</text>
        <view class="owner-content">
          <view class="owner-main">
            <image :src="ownerInfo.avatar || '/static/default-avatar.png'" class="owner-avatar" />
            <view class="owner-details">
              <text class="owner-name">{{ ownerInfo.nickname || '匿名用户' }}</text>
              <view class="owner-stats">
                <u-rate :value="ownerInfo.rating || 5" readonly size="16" />
                <text class="rating-text">({{ ownerInfo.rating || 5 }}分)</text>
                <text class="device-count">{{ ownerInfo.deviceCount || 1 }}台设备</text>
              </view>
            </view>
          </view>
          
          <view class="owner-actions">
            <u-button size="small" type="info" @click="viewOwnerProfile">
              查看主页
            </u-button>
            <u-button size="small" type="primary" @click="contactOwner">
              联系TA
            </u-button>
          </view>
        </view>
      </view>

      <!-- 相似设备推荐 -->
      <view class="recommend-card" v-if="recommendDevices.length > 0">
        <text class="card-title">相似设备推荐</text>
        <scroll-view scroll-x class="recommend-scroll">
          <view class="recommend-list">
            <view 
              v-for="device in recommendDevices" 
              :key="device.id"
              class="recommend-item"
              @click="goToDevice(device.id)"
            >
              <image :src="device.images?.[0] || '/static/placeholder-device.png'" class="recommend-image" />
              <text class="recommend-title">{{ device.title }}</text>
              <text class="recommend-price">￥{{ device.dailyRent }}/天</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 设备评价 -->
      <view class="reviews-card" v-if="deviceReviews.length > 0">
        <view class="card-header">
          <text class="card-title">用户评价 ({{ totalReviews }})</text>
          <text class="view-all-btn" @click="viewAllReviews">查看全部</text>
        </view>
        
        <view class="reviews-list">
          <view v-for="review in deviceReviews.slice(0, 3)" :key="review.id" class="review-item">
            <view class="review-header">
              <image :src="review.user.avatar" class="reviewer-avatar" />
              <view class="reviewer-info">
                <text class="reviewer-name">{{ review.user.nickname }}</text>
                <u-rate :value="review.rating" readonly size="12" />
              </view>
              <text class="review-date">{{ formatDate(review.createdAt) }}</text>
            </view>
            <text class="review-content">{{ review.comment }}</text>
          </view>
        </view>
      </view>

      <!-- 底部间距 -->
      <view class="bottom-spacing"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="bar-left">
        <view class="contact-btn" @click="contactOwner">
          <u-icon name="chat" size="20" />
          <text class="btn-label">咨询</text>
        </view>
        <view class="collect-btn" @click="toggleFavorite">
          <u-icon 
            :name="deviceInfo.isFavorite ? 'heart-fill' : 'heart'"
            :color="deviceInfo.isFavorite ? '#ff6b6b' : '#666'"
            size="20"
          />
          <text class="btn-label">{{ deviceInfo.isFavorite ? '已收藏' : '收藏' }}</text>
        </view>
      </view>
      
      <u-button 
        type="primary"
        :disabled="!canRent"
        @click="startRent"
        class="rent-button"
        :loading="rentLoading"
      >
        {{ getRentButtonText() }}
      </u-button>
    </view>

    <!-- 可用性查询弹窗 -->
    <u-popup v-model="showAvailabilityModal" mode="center" border-radius="20">
      <view class="availability-modal">
        <view class="modal-header">
          <text class="modal-title">查看可租时间</text>
          <u-icon name="close" @click="showAvailabilityModal = false" size="20" />
        </view>
        <view class="modal-content">
          <view class="date-selector">
            <u-calendar 
              v-model="availabilityDates"
              mode="range"
              :min-date="new Date()"
              :max-date="getMaxDate()"
              @confirm="checkDateAvailability"
            />
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 费用计算弹窗 -->
    <u-popup v-model="showCostModal" mode="bottom" border-radius="20">
      <view class="cost-modal">
        <view class="modal-header">
          <text class="modal-title">费用计算</text>
          <u-icon name="close" @click="showCostModal = false" size="20" />
        </view>
        <view class="modal-content">
          <view class="cost-form">
            <view class="form-item">
              <text class="form-label">租赁天数</text>
              <u-number-box 
                v-model="costCalculation.days" 
                :min="deviceInfo.minRentDays || 1"
                :max="365"
                @change="calculateRentCost"
              />
            </view>
            <view class="form-item">
              <text class="form-label">设备数量</text>
              <u-number-box 
                v-model="costCalculation.quantity" 
                :min="1"
                :max="10"
                @change="calculateRentCost"
              />
            </view>
          </view>
          
          <view class="cost-breakdown">
            <view class="cost-item">
              <text class="cost-label">租金小计</text>
              <text class="cost-value">￥{{ costCalculation.rentAmount }}</text>
            </view>
            <view class="cost-item">
              <text class="cost-label">押金</text>
              <text class="cost-value">￥{{ costCalculation.depositAmount }}</text>
            </view>
            <view class="cost-item total">
              <text class="cost-label">合计费用</text>
              <text class="cost-value total-amount">￥{{ costCalculation.totalAmount }}</text>
            </view>
          </view>
          
          <u-button type="primary" @click="proceedToRent" class="proceed-btn">
            确认租赁
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import apiService from '@/api/index.js'
import { checkLoginStatus } from '@/utils/auth.js'

export default {
  data() {
    return {
      deviceId: '',
      deviceInfo: {},
      ownerInfo: {},
      recommendDevices: [],
      deviceReviews: [],
      totalReviews: 0,
      deviceFeatures: [],
      currentImageIndex: 0,
      specsExpanded: false,
      loading: false,
      rentLoading: false,
      
      // 地图相关
      mapCenter: {
        longitude: 116.404,
        latitude: 39.915
      },
      mapScale: 15,
      mapMarkers: [],
      
      // 弹窗控制
      showAvailabilityModal: false,
      showCostModal: false,
      availabilityDates: [],
      
      // 费用计算
      costCalculation: {
        days: 1,
        quantity: 1,
        rentAmount: 0,
        depositAmount: 0,
        totalAmount: 0
      }
    }
  },
  
  computed: {
    canRent() {
      return this.deviceInfo.status === 'AVAILABLE' && !this.loading
    }
  },
  
  onLoad(options) {
    this.deviceId = options.id
    if (this.deviceId) {
      this.initPage()
    } else {
      uni.showToast({
        title: '设备ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  
  onShow() {
    // 更新收藏状态
    this.updateFavoriteStatus()
  },
  
  methods: {
    async initPage() {
      uni.showLoading({ title: '加载中...' })
      
      try {
        await Promise.all([
          this.loadDeviceDetail(),
          this.loadRecommendDevices(),
          this.loadDeviceReviews()
        ])
      } catch (error) {
        console.error('页面初始化失败:', error)
      } finally {
        uni.hideLoading()
      }
    },
    
    async loadDeviceDetail() {
      try {
        const result = await apiService.device.getDeviceDetail(this.deviceId)
        // 后端返回的数据结构是 { code, message, data }
        const device = result.data || result
        
        this.deviceInfo = device
        
        // 加载出租方信息（后端已包含在设备数据中）
        if (device.owner) {
          this.ownerInfo = {
            id: device.owner.id,
            nickname: device.owner.nickname || '匿名用户',
            avatar: device.owner.avatar || '/static/default-avatar.png',
            phone: device.owner.phone,
            rating: 4.8, // 后端暂未提供评分，使用默认值
            deviceCount: 1 // 后端暂未提供设备数量，使用默认值
          }
        }
        
        // 设置地图
        if (device.location?.lat && device.location?.lng) {
          this.mapCenter = {
            longitude: device.location.lng,
            latitude: device.location.lat
          }
          this.mapMarkers = [{
            id: device.id,
            longitude: device.location.lng,
            latitude: device.location.lat,
            title: device.title,
            iconPath: '/static/map-marker.png',
            width: 30,
            height: 30
          }]
        }
        
        // 设置设备特点
        this.deviceFeatures = this.extractFeatures(device)
        
        // 初始化费用计算
        this.costCalculation.days = device.minRentDays || 1
        this.calculateRentCost()
        
        // 检查收藏状态
        await this.checkFavoriteStatus()
        
      } catch (error) {
        console.error('加载设备详情失败:', error)
        uni.showToast({
          title: error.message || '加载设备详情失败',
          icon: 'none'
        })
      }
    },
    
    async loadOwnerInfo(ownerId) {
      try {
        // 后端已在设备详情中包含出租方信息，这里不再需要单独调用
        return {
          id: ownerId,
          nickname: '设备出租方',
          avatar: '/static/default-avatar.png',
          rating: 4.8,
          deviceCount: 1
        }
      } catch (error) {
        console.error('加载出租方信息失败:', error)
        return {}
      }
    },
    
    async loadRecommendDevices() {
      try {
        // 后端暂未实现热门设备接口，暂时使用空数据
        this.recommendDevices = []
        // 如果需要推荐设备，可以从设备列表中随机获取
        // const result = await apiService.device.getPopularDevices(6)
        // const devices = result.data || result || []
        // this.recommendDevices = devices.filter(d => d.id !== this.deviceId)
      } catch (error) {
        console.error('加载推荐设备失败:', error)
        this.recommendDevices = []
      }
    },
    
    async loadDeviceReviews() {
      try {
        // 后端暂未实现设备评价接口，暂时使用空数据
        this.deviceReviews = []
        this.totalReviews = 0
        
        // 如果后端实现了评价功能，可以取消注释以下代码
        // const result = await apiService.device.getDeviceReviews(this.deviceId, {
        //   page: 1,
        //   limit: 5
        // })
        // if (result.reviews || result.data) {
        //   this.deviceReviews = result.reviews || result.data || []
        //   this.totalReviews = result.total || 0
        // }
      } catch (error) {
        console.error('加载设备评价失败:', error)
        // 评价功能暂未实现，使用空数据
        this.deviceReviews = []
        this.totalReviews = 0
      }
    },
    
    extractFeatures(device) {
      const features = []
      
      if (device.specifications) {
        if (device.specifications.节能 || device.specifications.能耗低) {
          features.push('节能环保')
        }
        if (device.specifications.自动化) {
          features.push('自动化控制')
        }
        if (device.specifications.维护简单) {
          features.push('维护简便')
        }
      }
      
      if (device.status === 'AVAILABLE') {
        features.push('立即可租')
      }
      
      return features
    },
    
    onSwiperChange(e) {
      this.currentImageIndex = e.detail.current
    },
    
    previewImage(index) {
      const images = this.deviceInfo.images || []
      if (images.length === 0) return
      
      uni.previewImage({
        urls: images,
        current: index
      })
    },
    
    getStatusClass(status) {
      const statusMap = {
        'AVAILABLE': 'status-available',
        'RENTED': 'status-rented',
        'MAINTENANCE': 'status-maintenance',
        'OFFLINE': 'status-offline'
      }
      return statusMap[status] || 'status-unknown'
    },
    
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可租赁',
        'RENTED': '已租出',
        'MAINTENANCE': '维护中',
        'OFFLINE': '已下线'
      }
      return statusMap[status] || '未知状态'
    },
    
    getRentButtonText() {
      if (this.rentLoading) return '处理中...'
      
      switch (this.deviceInfo.status) {
        case 'AVAILABLE':
          return '联系客服'
        case 'RENTED':
          return '已被租用'
        case 'MAINTENANCE':
          return '维护中'
        case 'OFFLINE':
          return '暂不可租'
        default:
          return '联系客服'
      }
    },
    
    getFullAddress() {
      const location = this.deviceInfo.location
      if (!location) return '位置信息待完善'
      
      return `${location.province || ''}${location.city || ''}${location.district || ''}${location.address || ''}`
    },
    
    async toggleFavorite() {
      // 检查登录状态
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }, 1500)
        return
      }
      
      try {
        // 先更新UI状态，提供即时反馈
        const originalState = this.deviceInfo.isFavorite
        this.deviceInfo.isFavorite = !originalState
        
        if (originalState) {
          // 取消收藏
          await apiService.user.removeFavorite(this.deviceId)
          uni.showToast({
            title: '取消收藏成功',
            icon: 'success'
          })
        } else {
          // 添加收藏
          await apiService.user.addFavorite(this.deviceId)
          uni.showToast({
            title: '收藏成功',
            icon: 'success'
          })
        }
      } catch (error) {
        // 如果API调用失败，恢复原始状态
        this.deviceInfo.isFavorite = !this.deviceInfo.isFavorite
        
        console.error('收藏操作失败:', error)
        let errorMessage = '操作失败'
        
        if (error.message) {
          if (error.message.includes('401') || error.message.includes('Unauthorized')) {
            errorMessage = '登录已过期，请重新登录'
            // 清除登录状态
            uni.removeStorageSync('token')
            uni.removeStorageSync('refresh_token')
            uni.removeStorageSync('user_info')
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/login/index'
              })
            }, 2000)
          } else if (error.message.includes('网络')) {
            errorMessage = '网络连接失败，请检查网络'
          } else {
            errorMessage = error.message
          }
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    async updateFavoriteStatus() {
      const token = uni.getStorageSync('token')
      if (!token) {
        this.deviceInfo.isFavorite = false
        return
      }
      
      try {
        const result = await apiService.user.checkFavorite(this.deviceId)
        const data = result.data || result
        this.deviceInfo.isFavorite = data.isFavorite || false
      } catch (error) {
        console.log('更新收藏状态失败:', error)
        // 如果检查失败，保持当前状态
      }
    },
    
    shareDevice() {
      // 分享设备功能
      uni.showActionSheet({
        itemList: ['复制链接', '分享到微信', '分享到朋友圈'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              // 复制链接
              uni.setClipboardData({
                data: `设备详情：${this.deviceInfo.title}`,
                success: () => {
                  uni.showToast({ title: '链接已复制', icon: 'success' })
                }
              })
              break
            case 1:
            case 2:
              uni.showToast({
                title: '分享功能开发中',
                icon: 'none'
              })
              break
          }
        }
      })
    },
    
    checkAvailability() {
      this.showAvailabilityModal = true
    },
    
    async checkDateAvailability() {
      if (this.availabilityDates.length !== 2) {
        uni.showToast({
          title: '请选择租赁时间段',
          icon: 'none'
        })
        return
      }
      
      try {
        const [startDate, endDate] = this.availabilityDates
        // 后端暂未实现可用性查询功能，使用模拟响应
        const result = await apiService.device.checkAvailability(
          this.deviceId,
          startDate.toISOString().split('T')[0],
          endDate.toISOString().split('T')[0]
        )
        
        // 如果后端返回了真实数据，使用真实数据
        if (result && typeof result.available === 'boolean') {
          if (result.available) {
            uni.showToast({
              title: '该时间段可租赁',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: '该时间段不可租赁',
              icon: 'none'
            })
          }
        } else {
          // 后端暂未实现，使用模拟响应
          uni.showToast({
            title: '该时间段可租赁',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('查询可用性失败:', error)
        // 后端暂未实现，使用模拟响应
        uni.showToast({
          title: '该时间段可租赁',
          icon: 'success'
        })
      } finally {
        this.showAvailabilityModal = false
      }
    },
    
    calculateCost() {
      this.showCostModal = true
    },
    
    calculateRentCost() {
      const dailyRent = this.deviceInfo.dailyRent || 0
      const deposit = this.deviceInfo.deposit || 0
      
      this.costCalculation.rentAmount = dailyRent * this.costCalculation.days * this.costCalculation.quantity
      this.costCalculation.depositAmount = deposit * this.costCalculation.quantity
      this.costCalculation.totalAmount = this.costCalculation.rentAmount + this.costCalculation.depositAmount
    },
    
    proceedToRent() {
      this.showCostModal = false
      this.startRent()
    },
    
    navigateToDevice() {
      const location = this.deviceInfo.location
      if (!location?.lat || !location?.lng) {
        uni.showToast({
          title: '位置信息不完整',
          icon: 'none'
        })
        return
      }
      
      uni.openLocation({
        latitude: location.lat,
        longitude: location.lng,
        name: this.deviceInfo.title,
        address: this.getFullAddress()
      })
    },
    
    openLocationDetail() {
      // 地图点击事件，可以显示更详细的位置信息
      this.navigateToDevice()
    },
    
    contactOwner() {
      if (!apiService.auth.isLoggedIn()) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      // 联系出租方功能
      uni.showActionSheet({
        itemList: ['发送消息', '拨打电话'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              uni.showToast({
                title: '消息功能开发中',
                icon: 'none'
              })
              break
            case 1:
              if (this.ownerInfo.phone) {
                uni.makePhoneCall({
                  phoneNumber: this.ownerInfo.phone
                })
              } else {
                uni.showToast({
                  title: '暂无联系电话',
                  icon: 'none'
                })
              }
              break
          }
        }
      })
    },
    
    viewOwnerProfile() {
      // 查看出租方主页
      uni.showToast({
        title: '出租方主页功能开发中',
        icon: 'none'
      })
    },
    
    async startRent() {
      if (!this.canRent) return
      
      // 获取联系电话
      const contactPhone = this.deviceInfo.contactPhone || '400-0000-000'
      
      // 显示联系方式选择
      uni.showActionSheet({
        itemList: [
          `拨打电话: ${contactPhone}`,
          '复制电话号码',
          '查看联系信息'
        ],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              // 拨打电话
              uni.makePhoneCall({
                phoneNumber: contactPhone,
                fail: (err) => {
                  console.error('拨打电话失败:', err)
                  uni.showToast({
                    title: '拨打电话失败',
                    icon: 'none'
                  })
                }
              })
              break
            case 1:
              // 复制电话号码
              uni.setClipboardData({
                data: contactPhone,
                success: () => {
                  uni.showToast({
                    title: '电话号码已复制',
                    icon: 'success'
                  })
                }
              })
              break
            case 2:
              // 查看联系信息
              this.showContactInfo()
              break
          }
        }
      })
    },
    
    // 显示联系信息
    showContactInfo() {
      const contactPhone = this.deviceInfo.contactPhone || '400-0000-000'
      
      uni.showModal({
        title: '联系客服',
        content: `客服电话：${contactPhone}\n工作时间：9:00-18:00\n\n如需租赁此设备，请拨打客服电话进行咨询。`,
        confirmText: '拨打电话',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: contactPhone,
              fail: (err) => {
                console.error('拨打电话失败:', err)
                uni.showToast({
                  title: '拨打电话失败',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    },
    
    // 拨打联系电话
    callContact() {
      const contactPhone = this.deviceInfo.contactPhone || '400-0000-000'
      
      uni.makePhoneCall({
        phoneNumber: contactPhone,
        fail: (err) => {
          console.error('拨打电话失败:', err)
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          })
        }
      })
    },
    
    goToDevice(deviceId) {
      uni.redirectTo({
        url: `/pages/devices/detail?id=${deviceId}`
      })
    },
    
    viewAllReviews() {
      // 查看所有评价
      uni.navigateTo({
        url: `/pages/devices/reviews?deviceId=${this.deviceId}`
      })
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    },
    
    getMaxDate() {
      const maxDate = new Date()
      maxDate.setMonth(maxDate.getMonth() + 6) // 最多可预订6个月后
      return maxDate
    },
    

    
    // 检查收藏状态
    async checkFavoriteStatus() {
      try {
        // 检查用户是否登录
        const token = uni.getStorageSync('token')
        if (!token) {
          this.deviceInfo.isFavorite = false
          return
        }

        const response = await apiService.user.checkFavorite(this.deviceId)
        console.log('🔍 收藏状态检查:', response)
        
        const data = response.data || response
        this.deviceInfo.isFavorite = data.isFavorite || false
        
      } catch (error) {
        console.error('检查收藏状态失败:', error)
        // 如果检查失败，默认为未收藏状态
        this.deviceInfo.isFavorite = false
      }
    },

    // 分享设备
    shareDevice() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: `pages/devices/detail?id=${this.deviceId}`,
        title: this.deviceInfo.title,
        summary: this.deviceInfo.description,
        imageUrl: this.deviceInfo.images?.[0],
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        },
        fail: () => {
          // 复制链接作为备选方案
          uni.setClipboardData({
            data: `${this.deviceInfo.title} - 设备ID: ${this.deviceId}`,
            success: () => {
              uni.showToast({
                title: '链接已复制',
                icon: 'success'
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.device-detail-page {
  background: $bg-color;
}



.page-content {
  height: 100vh;
}

.image-section {
  position: relative;
  height: 600rpx;
}

.device-swiper {
  width: 100%;
  height: 100%;
}

.device-image {
  width: 100%;
  height: 100%;
}

.image-indicator {
  position: absolute;
  bottom: 32rpx;
  right: 32rpx;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8rpx 16rpx;
  border-radius: $border-radius-base;
  font-size: $font-size-sm;
}

.action-buttons {
  position: absolute;
  top: 32rpx;
  right: 32rpx;
  display: flex;
  gap: 16rpx;
}

.action-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-card, .specs-card, .description-card, .location-card, .owner-card, .recommend-card, .reviews-card {
  background: $bg-white;
  margin: 24rpx 32rpx;
  padding: 32rpx;
  border-radius: $border-radius-lg;
  box-shadow: $box-shadow-light;
}

.info-card {
  margin-top: -80rpx;
  position: relative;
  z-index: 10;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
}

.title-section {
  flex: 1;
}

.device-title {
  font-size: $font-size-xxl;
  font-weight: $font-weight-bold;
  color: $text-primary;
  display: block;
  margin-bottom: 8rpx;
}

.device-subtitle {
  font-size: $font-size-base;
  color: $text-secondary;
  display: block;
}

.status-badge {
  padding: 12rpx 20rpx;
  border-radius: $border-radius-base;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  
  &.status-available {
    background: rgba(92, 184, 92, 0.1);
    color: #5CB85C;
  }
  
  &.status-rented {
    background: rgba(217, 83, 79, 0.1);
    color: #D9534F;
  }
}

.price-section {
  margin-bottom: 32rpx;
}

.price-main {
  display: flex;
  align-items: baseline;
  margin-bottom: 12rpx;
}

.price-symbol {
  font-size: $font-size-lg;
  color: $primary-color;
  font-weight: $font-weight-medium;
}

.price-amount {
  font-size: 64rpx;
  font-weight: $font-weight-bold;
  color: $primary-color;
  margin: 0 8rpx;
}

.price-unit {
  font-size: $font-size-base;
  color: $primary-color;
}

.price-secondary {
  display: flex;
  gap: 32rpx;
}

.deposit-text, .rent-period {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.quick-actions {
  display: flex;
  gap: 24rpx;
}

.quick-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 20rpx;
  background: rgba(74, 144, 226, 0.05);
  border-radius: $border-radius-base;
  border: 2rpx solid rgba(74, 144, 226, 0.1);
}

.btn-text {
  font-size: $font-size-sm;
  color: $primary-color;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.card-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-bold;
  color: $text-primary;
}

.expand-btn {
  font-size: $font-size-sm;
  color: $primary-color;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.specs-content {
  overflow: hidden;
  max-height: 200rpx;
  transition: max-height 0.3s ease;
  
  &.expanded {
    max-height: none;
  }
}

.specs-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx 32rpx;
}

.spec-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.spec-label {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.spec-value {
  font-size: $font-size-base;
  color: $text-primary;
  font-weight: $font-weight-medium;
}

.description-text {
  font-size: $font-size-base;
  color: $text-secondary;
  line-height: 1.6;
  margin-bottom: 24rpx;
}

.features-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.feature-tag {
  padding: 8rpx 16rpx;
  background: rgba(74, 144, 226, 0.1);
  color: $primary-color;
  font-size: $font-size-xs;
  border-radius: $border-radius-sm;
}

.location-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.distance-text {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.location-address {
  font-size: $font-size-base;
  color: $text-secondary;
  margin-bottom: 24rpx;
  display: block;
}

.location-map {
  width: 100%;
  height: 300rpx;
  border-radius: $border-radius-base;
}

/* 联系信息样式 */
.contact-card {
  background: $bg-primary;
  border-radius: $border-radius-md;
  padding: $card-padding;
  margin-bottom: $section-margin;
  box-shadow: $box-shadow-light;
}

.contact-content {
  margin-top: 24rpx;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background: rgba(74, 144, 226, 0.05);
  border-radius: $border-radius-base;
  margin-bottom: 16rpx;
  transition: $transition-fast;
}

.contact-item:active {
  background: rgba(74, 144, 226, 0.1);
  transform: scale(0.98);
}

.contact-text {
  flex: 1;
  font-size: $font-size-md;
  color: $text-primary;
  font-weight: $font-weight-medium;
  margin-left: 16rpx;
}

.contact-label {
  font-size: $font-size-sm;
  color: $primary-color;
  font-weight: $font-weight-medium;
}

.working-hours {
  display: flex;
  align-items: center;
  padding-left: 24rpx;
}

.hours-text {
  font-size: $font-size-sm;
  color: $text-tertiary;
  margin-left: 8rpx;
}

.owner-content {
  margin-top: 24rpx;
}

.owner-main {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.owner-avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
}

.owner-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.owner-name {
  font-size: $font-size-base;
  font-weight: $font-weight-medium;
  color: $text-primary;
}

.owner-stats {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.rating-text, .device-count {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.owner-actions {
  display: flex;
  gap: 16rpx;
}

.recommend-scroll {
  margin-top: 24rpx;
}

.recommend-list {
  display: flex;
  gap: 24rpx;
  padding: 0 8rpx;
}

.recommend-item {
  width: 200rpx;
  flex-shrink: 0;
}

.recommend-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: $border-radius-base;
  margin-bottom: 12rpx;
}

.recommend-title {
  font-size: $font-size-sm;
  color: $text-primary;
  display: block;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recommend-price {
  font-size: $font-size-sm;
  color: $primary-color;
  font-weight: $font-weight-medium;
}

.view-all-btn {
  font-size: $font-size-sm;
  color: $primary-color;
}

.reviews-list {
  margin-top: 24rpx;
}

.review-item {
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid $border-color;
  margin-bottom: 24rpx;
  
  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.review-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 12rpx;
}

.reviewer-avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
}

.reviewer-info {
  flex: 1;
}

.reviewer-name {
  font-size: $font-size-sm;
  color: $text-primary;
  display: block;
  margin-bottom: 4rpx;
}

.review-date {
  font-size: $font-size-xs;
  color: $text-tertiary;
}

.review-content {
  font-size: $font-size-base;
  color: $text-secondary;
  line-height: 1.5;
}

.bottom-spacing {
  height: 120rpx;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $bg-white;
  padding: 24rpx 32rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.bar-left {
  display: flex;
  gap: 32rpx;
}

.contact-btn, .collect-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.btn-label {
  font-size: $font-size-xs;
  color: $text-secondary;
}

.rent-button {
  flex: 1;
  height: 88rpx;
  font-size: $font-size-base;
  font-weight: $font-weight-medium;
}

.availability-modal, .cost-modal {
  width: 680rpx;
  max-height: 80vh;
  background: $bg-white;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 2rpx solid $border-color;
}

.modal-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-bold;
  color: $text-primary;
}

.modal-content {
  padding: 32rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.cost-form {
  margin-bottom: 32rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 2rpx solid $border-color;
}

.form-label {
  font-size: $font-size-base;
  color: $text-primary;
}

.cost-breakdown {
  background: $bg-color;
  border-radius: $border-radius-base;
  padding: 24rpx;
  margin-bottom: 32rpx;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.total {
    border-top: 2rpx solid $border-color;
    padding-top: 16rpx;
    font-weight: $font-weight-medium;
  }
}

.cost-label {
  font-size: $font-size-base;
  color: $text-secondary;
}

.cost-value {
  font-size: $font-size-base;
  color: $text-primary;
  
  &.total-amount {
    color: $primary-color;
    font-size: $font-size-lg;
    font-weight: $font-weight-bold;
  }
}

.proceed-btn {
  width: 100%;
  height: 88rpx;
}
</style> 